﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Navigation;
using System.Collections.Generic;

namespace OARepository.HelloWorld
{
    [ToolboxItemAttribute(false)]
    public class HelloWorld : WebPart
    {
        enum Sections { Unknown, Menu, Browse, Item };
        private Sections sectionId = Sections.Unknown;
        private string listId = null;
        private string itemId = null;
        private string baseUrl = null;
        private string debug = "";

        private void Page_Load(object sender, EventArgs e)
        {
            debug += "Page_Load\n";
            SiteMap.SiteMapResolve += new SiteMapResolveEventHandler(this.ExpandRepositoryPaths);
        }
        private SiteMapNode ExpandRepositoryPaths(Object sender, SiteMapResolveEventArgs e)
        {
            this.debug += "ExpandRepositoryPaths\n";
            SiteMapNode currentNode = SiteMap.CurrentNode.Clone(true);
            SiteMapNode tempNode = currentNode;

            tempNode.Url = tempNode.Url + "?foo=bar";
            this.debug += "tempNode.Url=" + tempNode.Url + "\n";

            return currentNode;
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            debug += "OnLoad\n";
            SiteMap.SiteMapResolve += new SiteMapResolveEventHandler(this.ExpandRepositoryPaths);
        }
        protected override void CreateChildControls()
        {
            debug += "CreateChildControls\n";
        }
        private void ParseUrl()
        {
            this.baseUrl = HttpContext.Current.Request.FilePath;

            string path = HttpContext.Current.Request.PathInfo;
            List<String> parts = new List<string>(path.Split('/'));
            parts.RemoveAt(0); // PathInfo starts with '/'

            if (parts.Count == 0)
            {
                this.sectionId = Sections.Menu;
            }
            // /browse/MyColl
            else if (parts[0] == "browse" && parts.Count == 2)
            {
                this.sectionId = Sections.Browse;
                this.listId = parts[1];
            }
            // /item/MyColl/MyItem
            else if (parts[0] == "item" && parts.Count == 3)
            {
                this.sectionId = Sections.Item;
                this.listId = parts[1];
                this.itemId = parts[2];
            }
        }
        private SPList CurrentList()
        {
            SPList myList = null;

            try
            {
                myList = SPContext.Current.Web.Lists.GetList(new Guid(this.listId), true);
            }
            catch (ArgumentException)
            {
                return null;
            }

            return myList;
        }
        private SPItem CurrentItem()
        {
            SPItem myItem = null;

            try
            {
                SPList myList = this.CurrentList();
                if (myList == null)
                    return null;
                myItem = myList.GetItemByUniqueId(new Guid(this.itemId));
            }
            catch (ArgumentException)
            {
                return null;
            }

            return myItem;
        }
        protected override void Render(HtmlTextWriter writer)
        {
            SPSite mySite = SPContext.Current.Site;
            SPWeb myWeb = SPContext.Current.Web;

            base.Render(writer);

            this.ParseUrl();

            //SPContentMapProvider prov = SiteMap.Provider as SPContentMapProvider;
            /*SPNavigationNodeCollection topNav = myWeb.Navigation.TopNavigationBar;
            if (topNav != null)
            {
                myWeb.Navigation.TopNavigationBar.AddAsLast(new SPNavigationNode("title", "url"));
            }*/

            switch (this.sectionId)
            {
                case Sections.Menu:
                    this.RenderBrowseMenu(writer);
                    break;
                case Sections.Browse:
                    this.RenderBrowseList(writer);
                    break;
                case Sections.Item:
                    this.RenderViewItem(writer);
                    break;
                default:
                    this.Render404(writer);
                    break;
            }

            writer.RenderBeginTag(HtmlTextWriterTag.Pre);
            writer.WriteEncodedText(this.debug);
            writer.RenderEndTag();
        }
        void RenderBrowseMenu(HtmlTextWriter writer)
        {
            SPWeb myWeb = SPContext.Current.Web;
            string baseUrl = myWeb.Url;

            writer.RenderBeginTag(HtmlTextWriterTag.H2);
            writer.Write("Browse");
            writer.RenderEndTag();

            SPListCollection lists = myWeb.GetListsOfType(SPBaseType.DocumentLibrary);
            writer.RenderBeginTag(HtmlTextWriterTag.Ul);
            foreach (SPList list in lists)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Li);
                writer.AddAttribute(HtmlTextWriterAttribute.Href, baseUrl + "/_layouts/OARepository/List.aspx/" + list.ID.ToString(), true);
                writer.RenderBeginTag(HtmlTextWriterTag.A);
                writer.Write(list.ToString());
                writer.RenderEndTag();
                writer.RenderEndTag();
            }
            writer.RenderEndTag();
        }
        void RenderBrowseList(HtmlTextWriter writer)
        {
            SPWeb myWeb = SPContext.Current.Web;

            SPList myList = this.CurrentList();
            if (myList == null)
            {
                this.Render404(writer, "'" + this.listId + "' is not a valid list");
                return;
            }

            writer.RenderBeginTag(HtmlTextWriterTag.H2);
            writer.Write("Browse " + myList.ToString());
            writer.RenderEndTag();

            writer.RenderBeginTag(HtmlTextWriterTag.Ul);
            foreach (SPContentType type in myList.ContentTypes)
            {
                foreach (SPField field in type.Fields)
                {
                    writer.RenderBeginTag(HtmlTextWriterTag.Li);
                    writer.WriteEncodedText(type.Name + "." + field.ToString() + " [" + field.Id + "]");
                    writer.RenderEndTag();
                }
            }
            writer.RenderEndTag();

            // SPField f_title = myList.Fields["Title"];

            writer.RenderBeginTag(HtmlTextWriterTag.Ul);
            foreach (SPListItem item in myList.Items)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Li);
                writer.AddAttribute(HtmlTextWriterAttribute.Href, this.baseUrl + "/item/" + myList.ID.ToString() + "/" + item.UniqueId);
                writer.RenderBeginTag(HtmlTextWriterTag.A);
                writer.WriteEncodedText(item["Title"] as string);
                writer.RenderEndTag();
                writer.RenderEndTag();
            }
            writer.RenderEndTag();
        }
        void RenderViewItem(HtmlTextWriter writer)
        {
            SPWeb myWeb = SPContext.Current.Web;

            SPItem myItem = this.CurrentItem();
            if (myItem == null)
            {
                this.Render404(writer, "'" + this.itemId + "' is not a valid item");
                return;
            }

            writer.RenderBeginTag(HtmlTextWriterTag.H2);
            writer.WriteEncodedText(myItem["Title"] as string);
            writer.RenderEndTag();

            writer.AddAttribute(HtmlTextWriterAttribute.Href, myItem["URL Path"] as string, true);
            writer.RenderBeginTag(HtmlTextWriterTag.A);
            writer.Write("View");
            writer.RenderEndTag();
        }
        void Render404(HtmlTextWriter writer)
        {
            this.Render404(writer, "404 Not Found");
        }
        void Render404(HtmlTextWriter writer, string message)
        {
            HttpResponse response = HttpContext.Current.Response;
            response.Clear();
            response.ClearContent();
            response.ClearHeaders();
            response.Status = "404 Not Found";
            response.StatusCode = 404;
            response.Write(message);
            response.End();
        }
    }
}
